package etnorservice.etnor_service.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import etnorservice.etnor_service.domain.dto.ArticleQueryParam;
import etnorservice.etnor_service.domain.po.Article;
import etnorservice.etnor_service.domain.po.Category;
import etnorservice.etnor_service.domain.po.Tag;
import etnorservice.etnor_service.domain.po.UserInfo;
import etnorservice.etnor_service.mapper.BlogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Date;

@Service
public class BlogService {

    @Autowired
    private BlogMapper blogMapper;

    /**
     * 获取文章列表
     */
    public PageInfo<Article> getArticleList(ArticleQueryParam param) {
        // 参数校验和默认值设置
        if (param.getPageNum() == null || param.getPageNum() < 1) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null || param.getPageSize() < 1) {
            param.setPageSize(10);
        }
        if (param.getSortBy() == null) {
            param.setSortBy("latest");
        }

        // 开启分页
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<Article> articles = blogMapper.selectArticleList(param);

        // 构建分页信息
        PageInfo<Article> pageInfo = new PageInfo<>(articles);

        // 处理文章列表数据（例如：内容截断、敏感信息过滤等）
        for (Article article : articles) {
            processArticle(article);
        }

        return pageInfo;
    }

    /**
     * 获取文章详情
     */
    @Transactional
    public Article getArticleDetail(Long id) {
        // 获取文章详情
        Article article = blogMapper.selectArticleById(id);
        if (article != null) {
            // 增加浏览量
            blogMapper.incrementViewCount(id);
            // 获取文章标签
            List<Tag> tags = blogMapper.selectTagsByArticleId(id);
            article.setTags(tags);
            // 处理文章数据
            processArticle(article);
        }
        return article;
    }

    /**
     * 获取分类列表（使用缓存）
     */
    @Cacheable(value = "categories", key = "'all'", unless = "#result == null")
    public List<Category> getCategoryList() {
        return blogMapper.selectCategoryList();
    }

    /**
     * 获取标签列表（使用缓存）
     */
    @Cacheable(value = "tags", key = "'all'", unless = "#result == null")
    public List<Tag> getTagList() {
        return blogMapper.selectTagList();
    }

    /**
     * 获取热门标签
     */
    @Cacheable(value = "tags", key = "'hot'", unless = "#result == null")
    public List<Tag> getHotTags(int limit) {
        return blogMapper.selectHotTags(limit);
    }

    /**
     * 获取用户信息
     */
    public UserInfo getUserInfo(Long userId) {
        return blogMapper.selectUserById(userId);
    }

    /**
     * 处理文章数据
     */
    private void processArticle(Article article) {
        if (article != null) {
            // 列表页面不返回完整内容
//            if (article.getContent() != null && article.getContent().length() > 500) {
//                article.setContent(article.getContent().substring(0, 500) + "...");
//            }

            // 确保摘要不为空
            if (article.getExcerpt() == null || article.getExcerpt().isEmpty()) {
                String content = article.getContent();
                if (content != null && content.length() > 200) {
                    article.setExcerpt(content.substring(0, 200) + "...");
                } else {
                    article.setExcerpt(content);
                }
            }

            // 处理时间显示
            if (article.getCreatedAt() != null) {
                // 可以添加时间格式化逻辑
            }
        }
    }
}
